import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
// 导包
import login from './../views/use/login.vue'
import home from './../views/home/home.vue'
import movie from './../views/movie/movie.vue'
import qa from './../views/qa/qa.vue'
import user from './../views/use/user.vue'
import notfound from './../views/notfound/notfound.vue'
import layout from './../views/layout.vue'
import edit from './../views/use/edit.vue'
import article from './../views/home/article.vue'
import search from './../views/home/search.vue'
import searchResult from './../views/home/searchResult.vue'
import student from './../views/use/student.vue'
// 设置路由
const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'student',
    path: '/student',
    component: student
  },
  {
    name: 'searchResult',
    path: '/searchResult',
    component: searchResult
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'myarticle',
    path: '/article',
    component: article
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit
  },
  {
    name: 'layout',
    path: '/',
    component: layout,
    // 把需要导航栏的页面放到layout页面里面进行渲染
    children: [
      {
        name: 'home',
        path: '/home',
        component: home
      },
      {
        name: 'movie',
        path: '/movie',
        component: movie
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        meta: {
          isLOgin: true
        }
      },
      {
        // 当浏览器后缀为‘/’就默认跳到home页面
        path: '/',
        // 重定向
        redirect: '/home'
      }
    ]
  },

  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  // 如果用户乱输入后缀就跳转到notfound页面显示404
  {
    // ‘*’所有；乱写的后缀
    path: '*',
    // 重定向
    redirect: '/notfound'
  }
]

const router = new VueRouter({
  routes
})

export default router
import { getToken } from '@/utils/token.js'
import { Toast } from 'vant'
Vue.use(Toast)

/* 注册路由前置导航守卫 */
router.beforeEach((to, from, next) => {
  //to: 要跳转的路由 （要到那里去）
  // console.log(to)
  //from : 从哪个路由跳转（从哪里来）
  // console.log(from)
  /*next : ***必须要调用的，否则路由无法跳转*** 
  next() :没有传参。 通过检查 。 允许跳转to页面
  next('/path') :传参数. 没有通过检查 。跳转到指定页面
  */
  /* 并不是所有的页面都需要做登录判断，把需要登录判断的页面添加meta */
  if (to.meta.isLOgin) {
    //需要做登录判断
    if (getToken()) {
      //有登录,不拦截，允许正常跳转
      next()
    } else {
      //没登录，进行拦截。 跳转登录页
      //弹窗提示
      Toast.fail('登入失败')
      //跳转登录页
      next('/login')
    }
  } else {
    //不需要做登录判断，无条件跳转
    next()
  }
})
